package com.mz3co.sysadmin.service.impl;

import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.codehaus.plexus.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.mz3co.sysadmin.dao.SysCompanyMapper;
import com.mz3co.sysadmin.model.SysCompany;
import com.mz3co.sysadmin.model.SysCompanyExample;
import com.mz3co.sysadmin.model.SysEmployeeExample;
import com.mz3co.sysadmin.model.SysCompanyExample.Criteria;
import com.mz3co.sysadmin.model.SysCustomer;
import com.mz3co.sysadmin.model.ex.SysEmployeeEx;
import com.mz3co.sysadmin.model.ex.SysUsersEx;
import com.mz3co.sysadmin.page.Page;
import com.mz3co.sysadmin.service.SessionService;
import com.mz3co.sysadmin.service.SysCompanyService;
import com.mz3co.sysadmin.service.SysCustomerService;
import com.mz3co.sysadmin.service.utils.CommonUtils;
import com.mz3co.sysadmin.service.utils.CriteriaUtils;
import com.mz3co.sysadmin.service.utils.DateJsonValueProcessor;
import com.mz3co.sysadmin.service.utils.ExportExcel;
import com.mz3co.sysadmin.service.utils.ReflectionUtils;
import com.mz3co.sysadmin.service.utils.SysConst;

public class SysCompanyServiceImpl implements SysCompanyService {

	@Autowired
	private SysCompanyMapper sysCompanyMapper;
	
	@Autowired
	private SysCustomerService sysCustomerService;

	@Autowired
	private SessionService sessionService;

	@Override
	public SysCompany getCompany(Integer companyId) {
		// TODO Auto-generated method stub
		return sysCompanyMapper.selectByPrimaryKey(companyId);
	}

	@Override
	public Map<String, Object> getCompanyByPage(SysCompany company,
			Integer pageSize, Integer pageNow) {
		// TODO Auto-generated method stub

		SysCompanyExample example = new SysCompanyExample();
		Criteria criteria = example.createCriteria();

		CriteriaUtils.setCriteria(criteria,
				ReflectionUtils.getFiledValues(company, false));

		int totalrecords = sysCompanyMapper.countByExample(example);

		/**
		 * for my sql db
		 */
		Page page = new Page();

		page.setBegin((pageNow - 1) * pageSize);
		page.setLength(pageSize);
		example.setPage(page);

		List<SysCompany> companys = sysCompanyMapper.selectByExample(example);

		/**
		 * for sql server db
		 */

		// example.setPageIndex(pageNow);
		// example.setPageSize(pageSize);
		// example.setOrderByClause(" customer_id desc");
		//
		// List<SysCustomer> customers = customerMapper.selectPage (example);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", totalrecords);
		if (totalrecords % pageSize == 0)
			map.put("totalPages", totalrecords / pageSize);
		else
			map.put("totalPages", totalrecords / pageSize + 1);
		JsonConfig config = new JsonConfig();
		config.setIgnoreDefaultExcludes(false);
		config.registerJsonValueProcessor(Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));

		map.put("rows", JSONArray.fromObject(companys, config));

		return map;
	}

	@Override
	@Transactional
	public String update(SysCompany company) {
		// TODO Auto-generated method stub
		
		SysCompany oldCompany = sysCompanyMapper.selectByPrimaryKey(company.getCompanyId());
		
		if(!oldCompany.getCompanyName().equalsIgnoreCase(company.getCompanyName())){
			
			SysCustomer customer = new SysCustomer();
			
			customer.setCompanyName(company.getCompanyName());
			customer.setCompanyId(company.getCompanyId());
			
			sysCustomerService.updateCompanyFullname(customer);
		}
			
		this.setDefaultValue(oldCompany);
		return sysCompanyMapper.updateByPrimaryKeySelective(company) == 0 ? "修改失败，访问数据库失败！"
				: "修改成功！";
	}

	@Override
	public String insert(SysCompany company) {
		// TODO Auto-generated method stub

	
		if (this.isExistCompany(company)){
			
			this.update(company);
			return "该公司已存在！";
			
		}
			

		this.setSessionInfo(company);
		this.setDefaultValue(company);
		return sysCompanyMapper.insertSelectiveAndGetId(company) == 0 ? "数据库访问失败，公司信息插入失败！"
				: "新增公司成功!";
	}

	/**
	 * 设置默认值
	 * @param company
	 */
	private void setDefaultValue(SysCompany company){
		
		if(StringUtils.isEmpty(company.getCompanyType()))
			company.setCompanyType("其他");
		
		if(StringUtils.isEmpty(company.getIndustry()))
			company.setIndustry("其他");
		
	}
	
	private void setSessionInfo(SysCompany company) {
		
		company.setCreateTime(new Date());
		
		// 设置权限信息
		SysUsersEx user = sessionService.getSessionHttpUser();
		
		if(user == null){
			company.setCreatorId( -1);
			company.setAccessGroup("-1");
			return;
		}
		company.setCreatorId(user.getUserDetailId());
		company.setAccessGroup(user.getAccessGroup());
		
	}

	// 判断给定的company对象的客户是否存在，并设置存在的companyId
	private boolean isExistCompany(SysCompany company) {

		SysCompanyExample example = new SysCompanyExample();

		example.or().andCompanyNameEqualTo(company.getCompanyName());

		List<SysCompany> companys = sysCompanyMapper.selectByExample(example);

		if (companys == null || companys.size() == 0)
			return false;

		company.setCompanyId(companys.get(0).getCompanyId());

		return true;

	}

	@Override
	public String delete(String ids) {
		// TODO Auto-generated method stub

		if (StringUtils.isEmpty(ids))
			return "success";

		List<Integer>  companyIds = CommonUtils.idsArrayToList(ids);
		
		String existCustomers = sysCustomerService.getCustomers(companyIds);
				
		if(!"".equals(existCustomers))
			return "删除失败，" + existCustomers;
		
		SysCompanyExample example = new SysCompanyExample();
		example.or().andCompanyIdIn(companyIds);

		return sysCompanyMapper.deleteByExample(example) == 0 ? "failure"
				: "success";
	}

	@Override
	public SysCompany getByName(String companyName) {
		// TODO Auto-generated method stub
		
		SysCompanyExample example = new SysCompanyExample();

		example.or().andCompanyNameEqualTo(companyName);

		List<SysCompany> companys = sysCompanyMapper.selectByExample(example);
		
		if(companys == null || companys.size() == 0)
			return null;
		
		return companys.get(0);
	}

	@Override
	public void exportExcel(SysCompany company, OutputStream os) {
		
		SysCompanyExample example = new SysCompanyExample();

		Criteria criteria = example.createCriteria();
		
		CriteriaUtils.setCriteria(criteria,
				ReflectionUtils.getFiledValues(company, false));

		example.setOrderByClause(" company_id desc");
		List<SysCompany>  listEmployeeEx= sysCompanyMapper.selectByExample(example);
		
		
		ExportExcel<SysCompany> exportExcel = new ExportExcel<SysCompany>();
		
		exportExcel.exportExcel("导出嘉宾信息", SysConst.ExcelConst.HEAD_SYSCOMPANY,SysConst.ExcelConst.FIELDNAMES_SYSCOMPANY, listEmployeeEx, os,"yyyy-MM-dd");


		
	}

}
